package com.user.config;

import com.user.filter.JwtLoginFilter;
import com.user.filter.JwtVerifyFilter;
import com.user.handle.LogoutHandler;
import com.user.util.JedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private UserDetailsService userDetailsService;
    @Autowired
    private JwtProperties properties;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //http.csrf().disable().authorizeRequests().anyRequest().permitAll().and().logout().permitAll();
        http.csrf().disable().authorizeRequests()
                .antMatchers("/login","/user/logout").permitAll().anyRequest().authenticated()
        .and().addFilterBefore(new JwtLoginFilter(super.authenticationManager(),this.properties),UsernamePasswordAuthenticationFilter.class)
        .addFilter(new JwtVerifyFilter(super.authenticationManager(),this.properties))
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and().logout().logoutUrl("/user/logout").logoutSuccessHandler(new LogoutHandler(this.properties));
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(this.userDetailsService);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
       /*web.ignoring().antMatchers("/login");*/
    }

}
